package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @ApiOperation("新增菜品")
    @Transactional//0.开启事务（涉及到多张表的增删改操作时需要开事务）
    public void addDish(DishDTO dishDTO) {
        //1.构造菜品基本信息数据，将其存入dish表中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);//拷贝属性值
        dishMapper.insert(dish);//调用mapper
        log.info("dishID={},",dish.getId());


        //2.构造菜品对应的口味数据，将其存入dish_flavor表中
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
            //判断菜品口味数据是否为空
        if (dishFlavors!=null && dishFlavors.size()>0){
            //关联菜品ID
            dishFlavors.forEach(flavors->{
                flavors.setDishId(dish.getId());
            });
            //调用mapper
            dishFlavorMapper.insertBatch(dishFlavors);
        }

    }

    /**
     * 分页查询菜品列表
     * @param dto
     * @return
     */
    @Override
    public PageResult list(DishPageQueryDTO dto) {
        //1.设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //2.调用mapper，强转成Page
        Page<DishVO> page =dishMapper.list(dto);

        //封装PageResult对象，并返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    public void deleteById(List<Long> ids) {
        //1.判断是否是启售，启售的菜品不允许删除
        ids.forEach(id->{
            Integer status = dishMapper.getStatusById(id);
            if (status == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2.判断是否关联了套餐，关联的套餐不允许删除
        Integer count = setmealDishMapper.countSetmeal(ids);
        if (count > 0){
            throw  new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3.删除菜品数据
        dishMapper.deleteById(ids);

        //4.删除菜品对应的口味数据
        dishFlavorMapper.deleteByDishId(ids);
    }

    /**
     * 根据ID查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO seleteById(Long id) {
        //1.根据菜品ID查询菜品数据
        Dish dish= dishMapper.selectById(id);

        //2.根据菜品ID查询菜品口味数据
         List<DishFlavor> flavors= dishFlavorMapper.selectByDishId(id);

        //3.将查询到的数据封装成DishVO对象并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish ,dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dto
     */

    @Transactional//0.开启事务
    public void updateDish(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);

        //1.修改菜品表
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.delByDishId(dto.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dto.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }
    /**
     * 启用与禁用
     * @param  status, id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
       Dish dish=Dish.builder()//链式封装Dish对象
               .status(status)
               .id(id)
               .build();

       //调用mapper
        dishMapper.update(dish);
    }

    /**
     * 根据分类ID查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> listByCategoryId(long categoryId) {
        List<Dish> dish= dishMapper.listByID(categoryId);
        return dish;
    }

    /**
     * 条件查询菜品和口味----用户端
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listBy(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
